package com.zxl.thread;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class HttpAndThreadTest implements Callable<String>{
    
    private String spec;
    
    public HttpAndThreadTest(String spec){
        this.spec = spec;
    }
    
    public String doTest() throws IOException {
        URL url = new URL(spec);
        URLConnection connection = url.openConnection();
        InputStream is = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String lineStr = null;
        StringBuffer buffer = new StringBuffer();
        while ((lineStr = reader.readLine()) != null) {
            buffer.append(lineStr);
        }
        reader.close();
        return buffer.toString();
    }
    
    public String call() throws Exception {
        return doTest();
    }
    

    public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {
        int size = 1;
        ExecutorService service = Executors.newFixedThreadPool(size);
//        Callable<V>
        Future<?> future = null;
        long startTime = System.currentTimeMillis();
        @SuppressWarnings("rawtypes")
        List<Future> futures = new ArrayList<Future>();
//        for(int i=0; i<size; i++){
            future = service.submit(new HttpAndThreadTest("http://localhost:8086/mapp/control/v1/pkpass/ffpClubPass"));
            futures.add(future);
            //不能在此循环内进行future的打印。会阻塞线程
//        }
        service.shutdown();
        while (true) {
            if (service.isTerminated()) {
                System.out.println("共花费 " + (System.currentTimeMillis() - startTime) + "毫秒");
                break;
            }
        }
//        for (Future<?> temp : futures) {
//            System.out.println(temp.get().toString());
//        }
        
        JSONObject jsonObject = JSONObject.parseObject(futures.get(0).get().toString());
        JSONArray jsonArray = (JSONArray) jsonObject.get("stream");
        Object[] array = jsonArray.toArray();
        OutputStream os = new FileOutputStream("C:\\Users\\zxl\\Desktop\\test.pass");
        for (Object object : array) {
            os.write((int) object);
        }
        os.close();
        System.exit(0);
    }
}
